package leetcode;

import java.util.*;

/**
 * 括号匹配问题 20
 */
public class TestStack {
    public static void main(String[] args) {
        String str1 = "{<[()]>}";
        String str2 = "{[>}";
        System.out.println(judge(str1));
        System.out.println(judge(str2));
    }

    public static boolean judge(String str) {
        Stack<Character> stack = new Stack<>();
        // 设置全部已有左括号
        List<Character> list = new ArrayList<>();
        list.add('<');
        list.add('(');
        list.add('[');
        list.add('{');
        // 若第一个括号就为右括号返回false
        if (!list.contains(str.charAt(0))) {
            return false;
        }
        Map<Character, Character> map = new HashMap<>();
        map.put('<', '>');
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        for (int i = 0; i < str.length(); i++) {
            char tmp = str.charAt(i);
            if (!list.contains(tmp)) {
                if (tmp != map.get(stack.peek())) {
                    return false;
                } else {
                    stack.pop();
                }
            } else {
                stack.push(tmp);
            }
        }
        if (!stack.empty()) {
            return false;
        }
        return true;
    }
}
